// 计算文件的哈希值 - 使用新的hash计算工具，支持Web Worker和分片计算
export async function calculateFileHash(file: File): Promise<string> {
  // 导入新的hash计算工具
  const { calculateFileHash: newCalculateFileHash } = await import('./hashUtils');
  
  console.log(`🔐 开始计算文件哈希: ${file.name} (${(file.size / 1024 / 1024).toFixed(2)}MB)`);
  
  const fileHash = await newCalculateFileHash(file, {
    useWorker: file.size > 1024 * 1024, // 大于1MB使用Worker
    chunkSize: 1024 * 1024, // 1MB分片
    onProgress: (progress) => {
      console.log(`🔐 哈希计算进度: ${file.name} - ${progress.toFixed(1)}%`);
    }
  });
  
  console.log(`🔐 文件哈希计算完成: ${file.name} -> ${fileHash}`);
  return fileHash;
}

// 将文件分割成块
export function chunkFile(file: File, chunkSize: number = 1024 * 1024): Blob[] {
  const chunks: Blob[] = [];
  let start = 0;
  
  while (start < file.size) {
    const end = Math.min(start + chunkSize, file.size);
    chunks.push(file.slice(start, end));
    start = end;
  }
  
  return chunks;
}

// 格式化文件大小
export function formatFileSize(bytes: number): string {
  if (bytes === 0) return '0 Bytes';
  
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 判断文件类型
export function getFileType(fileName: string): 'image' | 'video' | 'audio' | 'document' | 'other' {
  const extension = fileName.split('.').pop()?.toLowerCase() || '';
  
  const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  const videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'webm', 'mkv'];
  const audioExtensions = ['mp3', 'wav', 'flac', 'aac', 'ogg', 'wma'];
  const documentExtensions = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'rtf'];
  
  if (imageExtensions.includes(extension)) return 'image';
  if (videoExtensions.includes(extension)) return 'video';
  if (audioExtensions.includes(extension)) return 'audio';
  if (documentExtensions.includes(extension)) return 'document';
  
  return 'other';
}

// 生成文件预览URL
export function generateFilePreview(file: File): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    
    reader.onload = (e) => {
      resolve(e.target?.result as string);
    };
    
    reader.onerror = () => {
      reject(new Error('Failed to read file'));
    };
    
    const fileType = getFileType(file.name);
    
    if (fileType === 'image') {
      reader.readAsDataURL(file);
    } else {
      // For non-image files, return a placeholder or file icon
      resolve('');
    }
  });
}

// 验证文件类型和大小
export function validateFile(file: File, maxSize: number = 100 * 1024 * 1024): { valid: boolean; error?: string } {
  // 检查文件大小 (默认最大100MB)
  if (file.size > maxSize) {
    return {
      valid: false,
      error: `文件大小不能超过 ${formatFileSize(maxSize)}`
    };
  }
  
  // 检查文件名
  if (!file.name || file.name.trim() === '') {
    return {
      valid: false,
      error: '文件名不能为空'
    };
  }
  
  return { valid: true };
}

// 将Blob转换为ArrayBuffer
export function blobToArrayBuffer(blob: Blob): Promise<ArrayBuffer> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(reader.result as ArrayBuffer);
    reader.onerror = () => reject(new Error('Failed to read blob'));
    reader.readAsArrayBuffer(blob);
  });
}